package com.hinnotek.warehouse.ui

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.hinnotek.warehouse.BR
import com.hinnotek.warehouse.R
import com.hinnotek.warehouse.bean.SpinnerUser
import com.hinnotek.warehouse.bean.WareHouseInfoBean
import com.hinnotek.warehouse.bean.WarehourseApplyFormDevices
import com.hinnotek.warehouse.databinding.ActivityNewStockInAddBinding
import com.hinnotek.warehouse.databinding.BottomAuditLayoutBinding
import com.hinnotek.warehouse.databinding.ItemNewlyAddLayoutBinding
import com.hinnotek.warehouse.utils.*
import com.hinnotek.warehouse.viewmodel.NewlyAddedModel
import com.lee.common.adapter.binding.SimpleBindingAdapter
import com.lee.common.base.BaseActivity
import com.lee.common.ext.getArg
import com.lee.common.ext.init
import com.lee.common.observer.DefaultObserver
import com.lee.common.utils.ACTIVITY_WAREHOUSE_NEW_STOCK_IN
import com.lee.common.utils.SharedPreUtils
import com.lee.common.utils.ToastUtils
import com.yanzhenjie.recyclerview.*
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber

/**
 * 新增 入库01/出库02/借用03/报损单04/预出库05
 */
@Route(path = ACTIVITY_WAREHOUSE_NEW_STOCK_IN)
@AndroidEntryPoint
class NewStockInAddActivity : BaseActivity<ActivityNewStockInAddBinding>() {

    private lateinit var adapter: SimpleBindingAdapter<WarehourseApplyFormDevices, ItemNewlyAddLayoutBinding>
    private val viewModel by viewModels<NewlyAddedModel>()

    val applyType by getArg<String>("applyType")

    //仓库数据 - 1
    private var wareHouseData = mutableListOf<WareHouseInfoBean>()

    //审核人  - 2
    private var approvalData = mutableListOf<SpinnerUser>()

    //抄送人 - 3
    private var sendUserData = mutableListOf<SpinnerUser>()

    //返回的料号列表
    private var materielNumData = mutableListOf<WarehourseApplyFormDevices>()

    //手动添加的料号
    private var materielNumAddList = mutableListOf<WarehourseApplyFormDevices>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_stock_in_add)
        viewModel.applyType = applyType ?: "01"
        //01入库单 02出库单 03借用单 04报损单
        bindingView.isShow = true
        when (applyType) {
            WAREHOUSE_TYPE_1 -> {
                setTitle("仓管入库")
                bindingView.isShow = false
            }
            WAREHOUSE_TYPE_2 -> setTitle("仓管出库")
            WAREHOUSE_TYPE_3 -> setTitle("借用出库")
            WAREHOUSE_TYPE_4 -> setTitle("报损出库")
            WAREHOUSE_TYPE_5 -> setTitle("预出库")
        }
        bindingView.vm = viewModel
        bindingView.executePendingBindings()
        viewModel.attachLoading(loadingState)
        viewModel.dialogMsg.observe(this, DefaultObserver(this))

        viewModel.loadData()
    }

    override fun initVew() {
        //必须在setAdapter之前调用
        bindingView.recycler.setSwipeMenuCreator(swipeMenuCreator)
        bindingView.recycler.setOnItemMenuClickListener(mMenuItemClickListener)
        adapter =
            SimpleBindingAdapter(R.layout.item_newly_add_layout, materielNumAddList, BR.newlyAdd)
        bindingView.recycler.init()
        bindingView.recycler.adapter = adapter

        emptyView.adapter = adapter
        viewModel.isEmpty.observe(this, {
            emptyView.values(it)
        })
        emptyView.getErrView().setOnClickListener {
            viewModel.refresh()
        }

        //初始化Adapter
        adapter.addListener { binding, itemData, pos ->
            val savePos = materielNumAddList[pos].index
            val list = arrayListOf<String>().apply {
                for (machineDetailBean in materielNumData) {
                    add(machineDetailBean.materielNum)
                }
            }
            //初始化Spinner
            binding.spinnerMaterielNum.setItems(list)
            if (savePos == -1) {
                binding.materielName.text = "请选择料号"
                binding.spinnerMaterielNum.text = ""
            } else {
                binding.spinnerMaterielNum.text = materielNumData[savePos].materielNum
                binding.materielName.text = materielNumData[savePos].materielName
            }
            //初始化一条提交信息
            getMateriel(0, itemData)
            if (binding.spinnerMaterielNum.editText.tag is TextWatcher) {
                binding.spinnerMaterielNum.editText.removeTextChangedListener(binding.spinnerMaterielNum.editText.tag as TextWatcher)
            }
            //料号spinner监听
            val textWatch = object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?, start: Int, count: Int, after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
                override fun afterTextChanged(s: Editable?) {
                    val input = s.toString()
                    if (input.length >= 9) {
                        for (index in materielNumData.indices) {
                            if (input == materielNumData[index].materielNum) {
                                itemData.index = index
                                binding.materielName.text = materielNumData[index].materielName
                                materielNumAddList[pos] = getMateriel(index, itemData)
                            }
                        }
                    }
                }
            }
            binding.spinnerMaterielNum.addTextChangedListener(textWatch)
            binding.spinnerMaterielNum.editText.tag = textWatch
            binding.devices.setText(itemData.deviceCount ?: "")

        }
        //添加footView
        val footBinding = DataBindingUtil.inflate<BottomAuditLayoutBinding>(
            layoutInflater, R.layout.bottom_audit_layout,
            null, false
        )
        adapter.addFooterView(footBinding.root)

        //提交数据
        footBinding.submit.setOnClickListener {
            val list =
                materielNumAddList.groupingBy { it.materielNum }.eachCount().filter { it.value > 1 }
            if (list.isNotEmpty()) {
                ToastUtils.showShort("料号不能重复添加!")
                return@setOnClickListener
            }
            //设备数量是否输入
            for (warehouse in materielNumAddList) {
                if (warehouse.deviceCount.isNullOrBlank()) {
                    ToastUtils.showShort("请填写设备数量")
                    return@setOnClickListener
                }
            }
            viewModel.addFormList = materielNumAddList
            viewModel.send()
        }

        //添加数据点击事件
        bindingView.addColumn.setOnClickListener {
            //不能大于当前料号列表数量
            if (materielNumData.size > materielNumAddList.size) {
                materielNumAddList.add(WarehourseApplyFormDevices())
                adapter.notifyItemInserted(materielNumAddList.size - 1)
            } else {
                ToastUtils.showShort("没有更多料号")
            }
        }
        //备注数据监听
        bindingView.remarks.addTextChangedListener {
            viewModel.projectRemarks = it.toString()
        }

        //仓库下拉监听
        bindingView.spinnerWare.setOnItemSelectedListener { _, position, _, _ ->
            setSendData(wareHouseData[position], null, null)
        }

        //审批人下拉
        bindingView.spinnerApproval.setOnItemSelectedListener { _, position, _, _ ->
            setSendData(null, approvalData[position], null)
        }

        //抄送人下拉
        bindingView.spinnerSend.setOnItemSelectedListener { _, position, _, _ ->
            setSendData(null, null, sendUserData[position])
        }

    }

    //获取网络数据,审核下拉数据
    @SuppressLint("NotifyDataSetChanged")
    override fun setData() {

        //提交
        viewModel.addWarehourseApplyFormPage.observe(this, {
            if (viewModel.isSuccess) {
                ToastUtils.showShort("提交成功")
                finish()
            } else {
                ToastUtils.showShort("提交失败")
            }
        })

        //仓库下拉数据
        viewModel.warehousePage.observe(this, Observer {
            if (it.size == 0) {
                return@Observer
            }
            val list = arrayListOf<String>().apply {
                for (machineDetailBean in it) {
                    add(machineDetailBean.wareName)
                }
            }
            wareHouseData = it
            setSendData(wareHouseData[0], null, null)
            bindingView.spinnerWare.setItems(list)
        })

        //抄送人数据
        viewModel.sendUserPage.observe(this, Observer {
            if (it.size == 0) {
                return@Observer
            }
            val list = arrayListOf<String>().apply {
                for (machineDetailBean in it) {
                    add(machineDetailBean.personName)
                }
            }
            sendUserData = it
            setSendData(null, null, sendUserData[0])
            bindingView.spinnerSend.setItems(list)
        })
        //料号数据
        viewModel.materielNumPage.observe(this, Observer {
            //初始化一条添加
            if (it.size == 0) {
                materielNumAddList.clear()
                adapter.notifyDataSetChanged()
                return@Observer
            }

            materielNumData = arrayListOf<WarehourseApplyFormDevices>().apply {
                for (devicesRe in it) {
                    this.add(
                        WarehourseApplyFormDevices(
                            devicesRe.deviceName, devicesRe.materielNum, devicesRe.deviceModel
                        )
                    )
                }
            }

            if (materielNumData.size > 0) {
                materielNumAddList.clear()
                adapter.notifyDataSetChanged()
                materielNumAddList.add(WarehourseApplyFormDevices())
                adapter.notifyItemInserted(0)
            }
        })
        //审批人
        viewModel.approvalUserPage.observe(this, Observer {
            if (it.size == 0) {
                return@Observer
            }
            val list = arrayListOf<String>().apply {
                for (machineDetailBean in it) {
                    add(machineDetailBean.personName)
                }
            }
            approvalData = it
            setSendData(null, approvalData[0], null)
            bindingView.spinnerApproval.setItems(list)
        })
    }

    //处理料号数据
    private fun getMateriel(
        position: Int, itemData: WarehourseApplyFormDevices
    ): WarehourseApplyFormDevices {
        itemData.materielNum = materielNumData[position].materielNum
        itemData.materielName = materielNumData[position].materielName
        itemData.materielModel = materielNumData[position].materielModel
        itemData.createUser = SharedPreUtils.getString("userName")
        return itemData
    }

    /**
     * 保存下拉操作数据
     */
    private fun setSendData(
        wareHouseData: WareHouseInfoBean?,
        approvalUser: SpinnerUser?, sendUser: SpinnerUser?
    ) {
        val userName = SharedPreUtils.getString("userName")
        val userId = SharedPreUtils.getInteger("userId", -1)
        if (wareHouseData != null) {
            viewModel.wareId = wareHouseData.wareId
            viewModel.wareName = wareHouseData.wareName
            viewModel.goodsType = wareHouseData.wareTypeString
            viewModel.ware()//获取仓库id后加载料号数据
        }
        if (approvalUser != null) {
            if (applyType == WAREHOUSE_TYPE_1) {
                viewModel.approval = userName
                viewModel.approvalUserId = userId
            } else {
                viewModel.approval = approvalUser.personName
                viewModel.approvalUserId = approvalUser.userId
            }
        }
        if (sendUser != null) {
            if (applyType == WAREHOUSE_TYPE_1) {
                viewModel.sendUser = userName
                viewModel.sendUserId = userId
            } else {
                viewModel.sendUser = sendUser.personName
                viewModel.sendUserId = sendUser.userId
            }
        }
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private val swipeMenuCreator =
        SwipeMenuCreator { _: SwipeMenu, swipeRightMenu: SwipeMenu, position: Int ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            //添加右侧的
            run {
                val deleteItem: SwipeMenuItem =
                    SwipeMenuItem(this).setBackground(R.drawable.menu_selector_red)
                        .setImage(R.drawable.ic_delete_white)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height)
                swipeRightMenu.addMenuItem(deleteItem) // 添加菜单到右侧。
            }
        }

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private val mMenuItemClickListener =
        OnItemMenuClickListener { menuBridge: SwipeMenuBridge, position: Int ->
            menuBridge.closeMenu()
            materielNumAddList.removeAt(position)
            adapter.notifyItemRemoved(position)
        }
}